//
//  MainWebViewController.m
//  CreditManager
//
//  Created by 李经纬 on 2017/8/29.
//  Copyright © 2017年 zhl. All rights reserved.
//

#import "MainWebViewController.h"
#import "WeakScriptMessageDelegate.h"


@interface MainWebViewController ()<WKNavigationDelegate,WKUIDelegate, WKScriptMessageHandler>
{
    WKUserContentController * userContentController;
    NSString *_title;
}
@property(nonatomic, strong) WKWebView *wkwebView;
@property (strong, nonatomic) UIProgressView *progressView;//这个是加载页面的进度条

@end

@implementation MainWebViewController

- (instancetype)initWithUrl:(NSString *)url{
    self = [super init];
    if (self) {
        [self disposeUrl:url];
        self.view.backgroundColor = [UIColor whiteColor];
        _progressViewColor = [UIColor colorWithRed:119.0/255 green:228.0/255 blue:115.0/255 alpha:1];
    }
    return self;
}

- (void)disposeUrl:(NSString *)url {
    

    if ([url containsString:@"&"]) {

//         NSArray *lab = [url componentsSeparatedByString:@"&"];
//        self.url = NSStringFormat(@"%@%@?token=%@&type=ios&taskId=%@",WebIP,lab[0],[[NSUserDefaults standardUserDefaults] valueForKey:@"userInfoToken"],lab[1]);
    }else if ([url containsString:WebIP]) {
        self.url = url;
    }else {

        self.url = NSStringFormat(@"%@%@?token=%@&type=ios",WebIP,url,[[NSUserDefaults standardUserDefaults] valueForKey:@"userInfoToken"]);
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];

   [self initWKWebView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.isHidenNaviBar = YES;
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    self.edgesForExtendedLayout = 0;
    [self initProgressView];
    
    //竹雕这句话的原因（如果网页掉原声相册，图片可以显示出来，不住，刷新了页面，图片出不来了）
//    [self.wkwebView reload];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.StatusBarStyle = self.StatusBarStyle;
    
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.progressView removeFromSuperview];

}


#pragma mark 初始化webview
-(void)initWKWebView
{
    WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];//先实例化配置类 以前UIWebView的属性有的放到了这里
    //注册供js调用的方法
    userContentController = [[WKUserContentController alloc]init];
    //注册方法（这里就是告诉js 我有一个控制器 叫做 NativeMethod!）
    [userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self]  name:@"NativeMethod"];
    
   
    configuration.userContentController = userContentController;
    configuration.preferences.javaScriptEnabled = YES;//打开js交互
    self.navigationController.navigationBar.translucent = NO;
    _wkwebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, kSCREEN_WIDTH, kSCREEN_HEIGHT-20) configuration:configuration];
    
    [self.view addSubview:_wkwebView];
    [self.view sendSubviewToBack:_wkwebView];
    _wkwebView.backgroundColor = [UIColor clearColor];
    _wkwebView.allowsBackForwardNavigationGestures =YES;//打开网页间的 滑动返回
    _wkwebView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
//    if (kiOS9Later) {
//        _wkwebView.allowsLinkPreview = YES;//允许预览链接
//    }
    _wkwebView.UIDelegate = self;
    _wkwebView.navigationDelegate = self;
    [_wkwebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];//注册observer 拿到加载进度
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
    [_wkwebView loadRequest:request];
    
//    NSString *html = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//    [_wkwebView loadHTMLString:html baseURL:baseURL];
}


#pragma mark --这个就是设置的上面的那个加载的进度
-(void)initProgressView
{
    CGFloat progressBarHeight = 3.0f;
    CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height + 20, navigaitonBarBounds.size.width, progressBarHeight);
    if (!_progressView || !_progressView.superview) {
        _progressView =[[UIProgressView alloc]initWithFrame:barFrame];
        _progressView.tintColor = [UIColor darkGrayColor];
        _progressView.trackTintColor = [UIColor clearColor];
        
        [self.view addSubview:self.progressView];
    }
}

//检测进度条，显示完成之后，进度条就隐藏了
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if (object == self.wkwebView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }

}



#pragma mark - ——————— WKNavigationDelegate ————————
// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
// 当内容开始返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.title = _title;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    // 禁用选中效果
    [self.wkwebView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
    [self.wkwebView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
    
}
// 页面加载失败时调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
    
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
//    DLog(@"%@",navigation);
}

// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
   //拦截地址的方法 NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    self.myUrl = navigationAction.request.URL.absoluteString;
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    
    if (![self.url isEqualToString:self.myUrl] && self.myUrl.length != 0) {
        decisionHandler(WKNavigationActionPolicyCancel);
        MainWebViewController *myWebVC = [[MainWebViewController alloc] initWithUrl:self.myUrl];
        [self.navigationController pushViewController:myWebVC animated:YES];

    }
    else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    

}


/*以下三个代理方法全都是与界面弹出提示框相关的，针对于web界面的三种提示框（警告框、确认框、输入框）分别对应三种代理方法 **/
    //  js 里面的alert实现，如果不实现，网页的alert函数无效  ,
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    if ([message isEqualToString:@"登陆超时"]) {
//        userManager.rspCode = -999;
//        [dataCenter onKick];
        
        return;
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    
    [self presentViewController:alertController animated:YES completion:nil];
}


#pragma mark -- WKScriptMessageHandler
// js放大招 调用我自己写的方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
   
    
}



#pragma mark - update nav items
-(void)reloadWebView{
    [self.wkwebView reload];
}


-(void)dealloc{
    [self clean];
}


#pragma mark ————— 清理 —————
-(void)clean{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self.wkwebView removeObserver:self forKeyPath:@"estimatedProgress"];
//    [self.wkwebView removeObserver:self forKeyPath:@"title"];
    //这里需要注意，前面增加过的方法一定要remove掉。
    [userContentController removeAllUserScripts];
    self.wkwebView.UIDelegate = nil;
    self.wkwebView.navigationDelegate = nil;
    [self cleanCacheAndCookie];
    
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie{
    
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

@end
